<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :destroyOnClose="true"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :label-col="labelCol" :wrapper-col="wrapperCol" :model="model">
        <!-- 子表单区域 -->
        <j-vxe-table
          ref="editableTable1"
          toolbar
          row-number
          row-selection
          keep-source
          :height="300"
          :loading="table1.loading"
          :dataSource="table1.dataSource"
          :columns="table1.columns"
          style="margin-top: 8px"
        />
        <!-- 主表单区域 -->
        <a-row class="form-row" :gutter="0">
          <a-col :lg="8">
            <a-form-model-item label="制单人" prop="createBy">
              <a-input placeholder="请输入制单人" disabled v-model="model.createBy" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="8">
            <a-form-model-item label="制单部门">
              <a-input placeholder="请输入制单部门" disabled v-model="model.departName" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="8">
            <a-form-model-item label="制单日期">
              <a-input placeholder="制单日期" disabled v-model="model.createTime" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import JEditableTable from '@/components/jeecg/JEditableTable'
import { VALIDATE_FAILED, getRefPromise, validateFormModelAndTables } from '@/components/jeecg/JVxeTable/utils/vxeUtils'
import { httpAction, getAction } from '@/api/manage'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import JDate from '@/components/jeecg/JDate'
import dateTime from '@/assets/tw/js/dateTime.js'
import store from '@/store/'
import moment from "moment"

export default {
  name: 'TslMdExchangeRateModal',
  components: {
    JDate,
    JEditableTable,
  },
  data() {
    return {
      departId: '',
      departName: '',
      userId: '',
      userName: '',
      title: '操作',
      user: '',
      visible: false,
      confirmLoading: false,
      openDictOptions:[],
      model: {
        userId: '',
        createBy: '',
        departId: '',
        departName: '',
        createTime: '',
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 - 6 },
      },
      activeKey: '1',
      // 客户信息
      table1: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '交易单位',
            key: 'unit',
            width: '24%',
            type: JVXETypes.input,
            defaultValue: '',
            placeholder: '请输入${title}',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '币种',
            key: 'type',
            width: '120px',
            type: JVXETypes.select,
            dictCode: 'currency',
            placeholder: '请选择${title}',
          },
          {
            title: '汇率',
            key: 'currency',
            width: '24%',
            type: JVXETypes.input,
            defaultValue: '',
            placeholder: '请输入${title}',
          },
        ],
      },
      url: {
        edit: '/bussiness/tslMdExchangeRate/editRateAndDetail',
        detailList: '/bussiness/tslMdExchangeRateDetail/querylistByExchangeRate',
        orderTicketList: '/test/jeecgOrderMain/queryOrderTicketListByMainId',
        getDepartById: '/sys/sysDepart/getDepartById',
        getExchangeRateDicByCode:'/sys/dict/loadDictItem/currency',
        add:'/bussiness/tslMdExchangeRate/addRateAndDetail',
      },
    }
  },
  created() {},
  mounted(){
    this.getAllCurrency();
  },
  methods: {
    //获取所有币种数据
    getAllCurrency(){
      initDictOptions('currency').then((res) => {
        console.log(res)
        if (res.success) {
          let currencyList = [];
          res.result.forEach((item) => {
          console.log("------------------")

            console.log(item)
            let currency = {
              title:item.title,
              value:item.value
            }
          currencyList.push(currency);
        })
        console.log("-------------------")

        console.log(currencyList)
        this.openDictOptions = currencyList;
        console.log("------最终币种------")
        console.log(this.openDictOptions)
        this.$forceUpdate();
        }
      })
    },
    // 获取所有的editableTable实例
    getAllTable() {
      
      return Promise.all([getRefPromise(this, 'editableTable1')])
    },

    add() {
      let id = store.getters.userInfo.departIds
      console.log(id)
      let param = { id: store.getters.userInfo.departIds }
      console.log('---------------')
      getAction(this.url.getDepartById, param).then((res) => {
        this.model.departId = store.getters.userInfo.departIds
        this.model.departName = res.result.departName
        this.model.userId = store.getters.userInfo.id
        this.model.createBy = store.getters.userInfo.realname
        this.model.createTime =moment().format('YYYY-MM-DD HH:mm:ss')
      })

      this.visible = true
      // this.$forceUpdate()
    },
    edit(record) {
      this.visible = true
      this.activeKey = '1'
      this.model = Object.assign({}, record)
      console.log(record)
      // 加载子表数据
      if (this.model.id) {
        let params = { rateId: this.model.id }
        this.requestTableData(this.url.detailList, params, this.table1)
      }
    },
    close() {
      this.visible = false
      this.getAllTable().then((editableTables) => {
        this.table1.dataSource = []
      })
      this.$emit('close')
    },
    /** 查询某个tab的数据 */
    requestTableData(url, params, tab) {
      tab.loading = true
      getAction(url, params)
        .then((res) => {
          tab.dataSource = res.result || []
        })
        .finally(() => {
          tab.loading = false
        })
    },
    handleOk() {
      console.log("提交")
      this.validateFields()
    },
    handleCancel() {
      this.close()
    },
    /** ATab 选项卡切换事件 */
    handleChangeTabs(key) {
      console.log("选项卡切换事件")
      getRefPromise(this, `editableTable${key}`).then((editableTable) => {
        editableTable.resetScrollTop()
      })
    },
    /** 触发表单验证 */
    validateFields() {
      this.getAllTable()
        .then((tables) => {          /** 一次性验证主表和所有的次表 */
          return validateFormModelAndTables(this.$refs.form,this.model, tables)
        }).then(allValues => {
          console.log("发送请求")
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          return this.requestAddOrEdit(formData)
        })
        .catch((e) => {
          if (e.error === VALIDATE_FAILED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : (e.index + 1).toString()
          } else {
            console.error(e)
          }
        })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      console.log("-------------------------")
      let orderMain = Object.assign(this.model, allValues.formValue)
      console.log("-----------整理前--------------")
      console.log(allValues.tablesValue[0])
      return {
        ...orderMain, // 展开
        details: allValues.tablesValue[0].tableData,
      }
    },
    /** 发起新增或修改的请求 */
    requestAddOrEdit(formData) {
      console.log("定义请求方法")
            console.log(formData)

      let url = this.url.add,
        method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      httpAction(url, formData, method)
        .then((res) => {
          if (res.success) {
            console.log(formData)
            this.$message.success(res.message)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
  },
}
</script>

<style scoped>
</style>